import DataDetailsCard from '../../components/cards/data-details-card/DataDetailsCard';
import { getDataIds } from '../../requests/dataIdsRequest';
import { getSingleData } from '../../requests/singleDataRequest';
import { GetStaticPropsContext, NextPage, NextPageContext } from 'next';
import { ParsedUrlQuery } from 'querystring';
import { SPersonResponse } from '../../utils/interface/personInterface';

interface IParams extends ParsedUrlQuery {
  dataId: string;
}

interface IProp {
  selectedData: SPersonResponse;
  message: string;
}

const SignelDataPage: NextPage<IProp> = (props) => {
  const data = props.selectedData;

  if (!data) {
    return <h1>{props.message}</h1>;
  }
  return <DataDetailsCard data={data.singleData} />;
};

export const getStaticProps = async (context: GetStaticPropsContext) => {
  const pageParams = context.params as IParams;

  try {
    const data = await getSingleData(pageParams.dataId);
    return {
      props: {
        selectedData: data,
        message: 'Successfull',
      },
      revalidate: 60,
    };
  } catch (error) {
    if (error instanceof Error)
      return {
        props: {
          selectedData: null,
          message: error.message,
        },
        revalidate: 60,
      };
    else
      return {
        props: {
          selectedData: null,
          message: error,
        },
        revalidate: 60,
      };
  }
};

export async function getStaticPaths() {
  try {
    const firstPageDataIds = await getDataIds();
    const paths = firstPageDataIds.dataIds.map((id) => ({
      params: { dataId: id },
    }));

    return {
      paths: paths,
      fallback: 'blocking',
    };
  } catch (error) {
    return {
      paths: [],
      fallback: 'blocking',
    };
  }
}

export default SignelDataPage;
